package com.graduation.smartparkingplatform.Controller;

import com.github.pagehelper.PageInfo;
import com.graduation.smartparkingplatform.Pojo.VisitorList;
import com.graduation.smartparkingplatform.Response.Response;
import com.graduation.smartparkingplatform.Response.ResponseUtils;
import com.graduation.smartparkingplatform.Service.VisitorService;
import com.graduation.smartparkingplatform.Utils.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/visitor")
public class VisitorController {
  @Autowired VisitorService visitorService;

  // 获取识别记录列表
  @GetMapping("/visitorList")
  public Response getVisitorList(
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "count", defaultValue = "10") Integer count) {
    try {
      PageInfo<VisitorList> visitorList = visitorService.getVisitorList(page, count);
      return ResponseUtils.buildSuccess(visitorList);
    } catch (Exception e) {
      return ResponseUtils.buildError(e);
    }
  }

  // 模糊搜索
  @GetMapping("/searchVisitor")
  public Response searchVisitor(
      @RequestParam(value = "page", defaultValue = "1") Integer page,
      @RequestParam(value = "count", defaultValue = "10") Integer count,
      @RequestParam(value = "userName", defaultValue = "null") String userName,
      @RequestParam(value = "ip", defaultValue = "null") String ip) {
    try {
      PageInfo<VisitorList> searchList = visitorService.searchVisitor(page, count, userName, ip);
      return ResponseUtils.buildSuccess(searchList);
    } catch (Exception e) {
      return ResponseUtils.buildError(e);
    }
  }

  // 删除识别记录
  @PostMapping("/deleteVisitor")
  public Response deleteVisitor(@RequestParam("visitorId") Integer visitorId) {
    Boolean delete = visitorService.deleteVisitor(visitorId);
    if (delete) {
      return ResponseUtils.buildSuccess("删除访客记录成功");
    }
    return ResponseUtils.buildError("删除访客记录失败");
  }

  // 导出Excel
  @RequestMapping("/exportVisitorExcel")
  public void exportVisitorExcel(HttpServletResponse response) {

    List<VisitorList> visitorList = visitorService.getVisitorListAll();
    // 获取当前时间
    Calendar calendar = Calendar.getInstance();
    // 定义时间格式化
    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HH:mm:ss");
    String nowTime = formatter.format(calendar.getTime());
    // 导出操作
    ExcelUtils.exportExcel(
        visitorList,
        "访客记录",
        "sheet1",
        VisitorList.class,
        "visitorDATA" + nowTime + ".xls",
        response);
    log.info("exportVisitorExcel");
  }
}
